<?php
namespace App\Cas;

require_once dirname(__FILE__) . "/CasService.php";

class Cas
{

    public static function getServiceUrl()
    {
        $server_root = env('SERVER_ROOT');
        if(empty($server_root)) {
            $url = self::getServerRootUrl();
            $url .= env('APP_ROOT') . env('CAS_SERVICE_URI');
            return $url;
        } else {
            return $server_root . env('APP_ROOT') . env('CAS_SERVICE_URI');
        }
    }

    public static function casLoginUrl()
    {
        $service = self::getServiceUrl();
        return env('CAS_SERVER').env('CAS_LOGIN_URI').'?service='.$service;
    }

    public static function auth()
    {
        $service = self::getServiceUrl();
        if(Auth::check())
        {
            $ticket = $_GET['ticket'];
            if(empty($ticket))
            {
                return redirect(env('CAS_SERVER').env('CAS_LOGIN_URI').'?service='.$service);
                exit;
            }
            else
            {
                $responseBody = CasService::casValidate($ticket, $service);
                if(!$responseBody->getSuccess())
                {
                    return redirect(self::casLoginUrl());
                    exit;
                }
                //从responseBody中获取用户信息

            }
        }
        else
        {
            return redirect()->guest(env('CAS_SERVICE_URI'));
        }
    }

    /**
     * @return string
     */
    private static function getServerRootUrl(): string
    {
        $protocol = 'http';
        $port = $_SERVER["SERVER_PORT"];
        $isDefaultPort = false;
        if ($port == '80' || $port == '443') {
            $isDefaultPort = true;
        }
        if (stristr($_SERVER['SERVER_PROTOCOL'], 'https')) {
            $protocol = 'https';
        }

        $url = $protocol . '://' . $_SERVER["SERVER_NAME"];
        if (!$isDefaultPort) {
            $url .= ':' . $port;
        }
        return $url;
    }
}


